/**
 * 作者： liushun
 * 时间： 2020/5/17
 * 功能： 有关用户操作的路由
 * **/

import express from 'express'
import User from '../models/user'
import Socket from "../models/socket";
import {sign, verify} from '../util/TokenUtil'
import {auth} from '../middleware'
import config from '../config'
import Article from '../models/acticle'
import Comment from '../models/comment'
import ThumbUp from '../models/thumbup'
import {message} from '../util/message'
import moment from 'moment'

const router = express.Router();

/**
 * @api {POST} /api/user/login 登录
 * @apiDescription 账号注册
 * @apiName login
 * @apiGroup User
 * @apiParam {string} username 用户名
 * @apiParam {string} password 密码
 * @apiSuccess {json} result
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "errno" : "0",
 *      "msg"   : "登录成功",
 *      data : {}
 *  }
 * @apiSampleRequest /api/user/login
 * @apiVersion 1.0.0
 */
router.post('/login', async function (req, res, next) {

  //解析传过来的参数
  const {username, password} = req.body;

  //用户名不能为空
  if(username === ''){
    res.json(message(1, "用户名不能为空"))
    return next()
  }

  //密码不能为空
  if(password === ''){
    res.json(message(1, "密码不能为空"))
    return next()
  }

  //从数据库中查询此用户用户名
  const userRes = await User.findOne({username})
  if(!userRes){
    res.json(message(1, `用名${username}还未注册`))
    return next()
  }

  //判断密码是否正确
  if(userRes.password !== password){
    res.json(message(1, "密码不正确"))
    return next()
  }else{
    res.json(message(0, "登录成功", {
      username: userRes.username,
      sex: userRes.sex,
      avatar: userRes.avatar,
      address: userRes.address,
      sign: userRes.sign,
      id: userRes.id,
      create: moment(userRes.createAt).format('YYYY-MM-DD HH:mm:ss'), //时间格式转换
      update: moment(userRes.createAt).format('YYYY-MM-DD HH:mm:ss') //时间格式转换
    }))
    return next()
  }
});


/**
 * @api {POST} /api/user/register 账号注册
 * @apiDescription 账号注册
 * @apiName register
 * @apiGroup User
 * @apiParam {string} username 用户名
 * @apiParam {string} password 密码
 * @apiParam {string} password_confirm 确认密码
 * @apiSuccess {json} result
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "errno" : "0",
 *      "msg"   : "注册成功"
 *  }
 * @apiSampleRequest /api/user/register
 * @apiVersion 1.0.0
 */
router.post('/register', async function (req, res, next) {

  //从 body 中解析参数
  const {username, password, password_confirm} = req.body;


  //用户名不能为空
  if(username === ''){
    res.json(message(1, "用户名不能为空"))
    return next()
  }

  //密码不能为空
  if(password === ''){
    res.json(message(1, "密码不能为空"))
    return next()
  }

  //两次密码不一致
  if(password !== password_confirm){
    res.json(message(1, "两次密码不一致"))
    return next()
  }

  //去数据库中查询此用户名是否已注册
  const userRes = await User.findOne({username});
  if(userRes){
    res.json(message(1, `用户名${username}已存在`))
    return next()
  }

  //保存新注册的用户
  let userSaveModal = {
    username,
    password
  }

  const saveRes = await new User(userSaveModal).save()
  if(saveRes){
    res.json(message(0, "注册成功"))
    return next()
  }else {
    res.json(message(1, "注册失败"))
    return next()
  }
})


//退出
router.get('/loginOut', async function (req, res, next) {

  //解析参数
  const userId = req.query.userId;


  try {
    const socketRes = await Socket.deleteOne({userId})

    if(socketRes){
      res.json({
        errno: 0,
        msg: '退出成功'
      })
    }else{
      res.json({
        errno: 1,
        msg: '退出失败'
      })
    }

  }catch (e) {
    res.json({
      errno: 1,
      msg: '退出异常'
    })
  }

})


router.post('/refreshToken', async function (req, res, next) {
  const refresh_token = req.body.refresh_token
  const reuslt = verify(refresh_token);
  if (reuslt.success) {
    const id = reuslt.decoded.userId
    const useRes = await User.findOne({_id: id})
    if(useRes){
      const access_expire = config.access_expire
      const access_token = sign(id, access_expire)

      res.json({
        errno: 0,
        data:{
          access_token,
          access_expire
        },
        msg: '刷新 Token 成功'
      })

    }else{
      res.json({
        errno: 1,
        msg: '授权用户不存在'
      })
    }
  } else {
    res.json({
      errno: 1,
      msg: '登录已失效'
    })
  }

})

router.post('/publishArticle', auth,async function (req, res, next) {
  const {userId, articleContent} = req.body

  const time = new Date().getTime()

  console.log(time)

  const article = {
    userId,
    articleContent,
    time
  }

  await new Article(article).save()

  res.json({
    errno: 0,
    msg: '发表成功'
  })

})

router.get('/getArticle', auth, async function (req, res, next) {

  const page = req.query.page
  const articles = await Article.find().populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })
    .skip(page*10)
    .limit(10)
    .sort({'_id':-1});

  res.json({
    errno: 0,
    data: articles,
    msg: '获取成功'
  })

})

router.post('/comment', auth, async function (req, res, next) {
  const {userId, articleId, commentContent} = req.body

  const commentModal = {
    userId,
    articleId,
    commentContent
  }

  await new Comment(commentModal).save()

  res.json({
    errno: 0,
    msg: '评论成功'
  })

})

router.get('/getComment', auth, async function (req, res, next) {
  const articleId = req.query.articleId

  const comments = await Comment.find({articleId}).populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })

  res.json({
    errno: 0,
    data: comments,
    msg: '获取评论成功'
  })

})


router.post('/thumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    res.json({
      errno: 1,
      msg: '您已经点过赞了'
    });
    return;
  }

  await new ThumbUp(thumbModal).save()

  res.json({
    errno: 0,
    msg: '点赞成功'
  })

})

router.post('/cancelThumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    await ThumbUp.remove(thumbModal)
  }

  res.json({
    errno: 0,
    msg: '取消成功'
  })

})

router.get('/getThumb', auth, async function (req, res, next) {
  const articleId = req.query.articleId

  const thumbs = await ThumbUp.find({articleId}).populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })

  res.json({
    errno: 0,
    data: thumbs,
    msg: '获取点赞列表成功'
  })

})

router.post('/isThumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    res.json({
      errno: 0,
      msg: '已赞'
    });
  }else{
    res.json({
      errno: 0,
      msg: '未赞'
    });
  }

})


router.post('/changeAvatar', auth, async function (req, res, next) {
  const _id = req.body.userId
  const avatar = req.body.avatar
  const user = await User.updateOne({_id},{avatar})
  console.log(user)
  res.json({
    errno: 0,
    msg: '更新头像成功'
  })

})

router.post('/changeName', auth, async function (req, res, next) {
  const _id = req.body.userId
  const username = req.body.username

  await User.update({_id},{username})

  res.json({
    errno: 0,
    msg: '更新名字成功'
  })

})





export default router
